package com.song.Niodemo01.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class TestClient {
	
	
	private Selector selector =null;
	
	private SocketChannel sc =null;
	
	
	public void init()
	{
		try {
			selector = Selector.open();
			sc = SocketChannel.open(new InetSocketAddress(9999));
			sc.configureBlocking(false);
			sc.register(selector, SelectionKey.OP_READ);
			
			new ClientThread().start();
			Scanner scanner  = new Scanner(System.in);
			while(scanner.hasNextLine())
			{
				String line = scanner.nextLine();
				sc.write(StandardCharsets.UTF_8.encode(line));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	class ClientThread extends Thread{

		@Override
		public void run() {
			
			try {
				while(selector.select()>0)
				{
					for( SelectionKey sk : selector.selectedKeys())
					{
						selector.selectedKeys().remove(sk);
						if(sk.isReadable())
						{
							SocketChannel sc = (SocketChannel)sk.channel();
							ByteBuffer bb = ByteBuffer.allocate(1024);
							String content ="";
							while( sc.read(bb) >0 )
							{
								sc.read(bb);
								bb.flip();
								content += StandardCharsets.UTF_8.decode(bb);
							}
							System.out.println(" 聊天 ： " +content);
						}
						
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	
	public static void main(String[] args) {
		new TestClient().init();
	}
}
